<?php

namespace App\Trip\Plane\Variflight;

use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Config\Repository;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class Variflight
{
    /**
     * @var Repository|Application|mixed
     */
    protected mixed $appid;
    /**
     * @var Repository|Application|mixed
     */
    protected mixed  $appsecurity;
    protected Client $client;
    protected string $url;
    protected string $business;

    /**
     * @throws Exception
     */
    public function __construct()
    {
        $this->appid       = config('trip.airplane.variflight.appid');
        $this->appsecurity = config('trip.airplane.variflight.secret');
        if (!$this->appid || !$this->appsecurity) {
            throw new Exception("航班舒适度服务未配置");
        }
        $this->client = new Client(["verify" => false]);
    }

    /**
     * @throws GuzzleException
     * @throws Exception
     */
    protected function query($param)
    {
        $token = new Token($this->appid, $this->appsecurity, $param);

        // 去除日期做缓存
        $p = $param;
        unset($p['date']);
        $ck = "Variflight:{$this->business}:{$token->buildParamString($p)}";
        if (Cache::has($ck)) {
            return Cache::get($ck);
        }
        $url = sprintf("%s?%s", $this->url, $token->getParamString());
        Log::info("Variflight:{$this->business}---> {$url}");
        $contents = $this->client->get($url)->getBody()->getContents();
        $res      = json_decode($contents, true);
        if (isset($res['error_code']) && $res['error_code'] > 0) {
            Log::error("Variflight:{$this->business}:error--->{$contents}");
            throw new Exception($res['error'] ?? 'error');
        } else {
            Cache::forever($ck, $res);
        }
        return $res;
    }
}